/*
 * @Author: cygao
 * @Date: 2018-11-10 21:08:25
 * @Last Modified by: caijw
 * @Last Modified time: 2019-01-05 19:06:16
 */

import React, { Component }             from 'react';
import List                             from '../list/list';
import Swiper                           from 'swiper/dist/js/swiper.js';
import { connect }                      from "react-redux";
import { Toast }                        from 'react-weui';
import * as actions                     from '../../../store/action/homepage';
import { 
    collect,
    exchangeCoupon,
}                                       from '../../../api/home';
import Header                           from '../../../components/Header/ProductHeader';
import 'swiper/dist/css/swiper.min.css';
import './detail.less';
import {Link, withRouter}               from 'react-router-dom';
import Utils                            from '../../../utils';

class Register extends Component {
    constructor() {
        super()
        this.state = {
          listClass: 'list-row', //列表排列样式
          listData: [ // 列表数据
            {
              image: '../../../static/images2/list-img.png',
              logo: '../../../static/images2/list-logo.png',
              title: '测试女装大佬哇卡阿卡卡阿卡试女装大佬哇卡阿卡卡阿卡试女装大佬哇卡阿卡卡阿卡卡',
              oldprice: '30',
              salenumber:'111111',
              newprice:'20',
              coupon:'10'
            },
            {
              image: '../../../static/images2/list-img.png',
              logo: '../../../static/images2/list-logo.png',
              title: '测试女装大佬哇卡阿卡卡阿试女装大佬哇卡阿卡卡阿卡试女装大佬哇卡阿卡卡阿卡卡卡',
              oldprice: '30',
              salenumber:'111111',
              newprice:'20',
              coupon:'10'
            },
            {
              image: '../../../static/images2/list-img.png',
              logo: '../../../static/images2/list-logo.png',
              title: '测试女装大佬哇卡阿卡卡阿试女装大佬哇卡阿卡卡阿卡试女装大佬哇卡阿卡卡阿卡卡卡',
              oldprice: '30',
              salenumber:'111111',
              newprice:'20',
              coupon:'10'
            },
            {
              image: '../../../static/images2/list-img.png',
              logo: '../../../static/images2/list-logo.png',
              title: '测试女装大佬哇卡阿卡卡试女装大佬哇卡阿卡卡阿卡试女装大佬哇卡阿卡卡阿卡阿卡卡',
              oldprice: '30',
              salenumber:'111111',
              newprice:'20',
              coupon:'10'
            },
            {
              image: '../../../static/images2/list-img.png',
              logo: '../../../static/images2/list-logo.png',
              title: '测试女装大佬哇卡阿卡卡试女装大佬哇卡阿卡卡阿卡试女装大佬哇卡阿卡卡阿卡阿卡卡',
              oldprice: '30',
              salenumber: '111111',
              newprice: '20',
              coupon: '888',
              id: 1
            }
          ],
          isLike: false
        }
        // bind
        this.onShare = this.onShare.bind(this);
        this.isLogin = this.isLogin.bind(this);
        this.onExchangeCounpon = this.onExchangeCounpon.bind(this);
        this.viewhistory = this.viewhistory.bind(this);
    }
    componentWillMount(){
        // if(!this.props.homepage.fetched){
        // const itemId = this.props.location.pathname.split('/')[2];
        let itemId = this.props.match.params.id;
        this.id =  this.props.match.params.id;
        this.props.fetchDetail(itemId);
        // 记录商品浏览
        this.viewhistory();
          //   console.log(this.props)
          // }
    }
    // 组件挂载
    componentDidUpdate () {
        setTimeout(()=>{
            this.swiper = new Swiper(this.refs.lun, {
                autoplay: true,
                loop:true,
                observer: true,
                pagination: {
                el: '.swiper-pagination',
                type: 'fraction'
               },
             });
        },0)
   }
            // // 生成swiper对象
            // new Swiper('.my-swiper1', {
            //     autoplay: true,
            //     loop: true,
            //     pagination : {
            //         el: '.swiper-pagination',
            //         type: 'fraction'
            //     }
            // },0);
        // })
    // }
    componentWillReceiveProps(){
        const itemId = this.props.location.pathname.split('/')[2];
        const token = localStorage.getItem('token');
        if(token){
        // 浏览
            const isLike = localStorage.getItem(itemId);
            if(isLike){
                this.setState({
                    isLike: true,
                    likeIcon: '../../../static/images2/logo-like-2.png'
                })
            }else{
                this.setState({
                    isLike: false,
                    likeIcon: '.../../../static/images2/logo-cate-2.png'
                })
            }
        }


        if (this.props.history.location !== this.props.location) {
            let itemId = this.props.match.params.id;
            this.props.fetchDetail(itemId);
            this.mainContent.scrollTop = 0;
        }
    }
    back = () =>{
        this.props.history.go(-1);
    }
    //判断是否登陆
    isLogin () {
        return !!localStorage.getItem('token');
    }
    viewhistory() {
        const item_id = this.props.location.pathname.split('/')[2];
        if (this.isLogin()) {
            collect({
                type: 2, // 浏览商品并记录。
                item_id
            })
            .then((res) => {
                console.log(res);
                if (res && res.data == 0) {
                    this.setState({
                        isLike: resp.data.load_page_has_liked
                    })
                } 
            })
            .catch((err) => {
                console.warn(err);
                if (err.response.data.ret == 999) {
                    this.props.history.push('/glogin');
                } 
                this.setState({
                    isLike: false
                });
            })
        }
    }
    onCollect(id){
        console.log('is login', this.isLogin());
        if (!this.isLogin()) {
            this.props.history.push('/glogin');
        } else {
            collect({
                type: 1,
                item_id: id
              }).then(resp => {
                  console.log(resp);
                  localStorage.setItem(id, resp.data.is_exists);
                  if(resp.data.load_page_has_liked){
                      this.setState({
                          isLike: true
                      })
                  }else{
                      this.setState({
                          isLike: false
                      })
                  }
              })
        }
    }
    onShare() {
        const {
            title,
            small_images,
            coupon_short_url,
        } = this.props.homepage.detail;
        if (!title || !small_images.length) {
            console.log("share detials undefined");
            return;
        }
        Utils.shareHref({
            href: `http://huiyouduoapp.com/shop/redirect.html?app3Redirect=` + encodeURIComponent(`http://huiyouduoapp.com/shop/#/gDetailShare/${this.id}`),
            title: title,
            content: title,
            thumb: small_images[0],
            picture: small_images[0],
        })
        .then(() => {
            console.log("分享成功");
        })
        .catch((e) => {
            console.log("分享失败:" + e);
        });
    }
    onExchangeCounpon() {
        const itemId = this.props.location.pathname.split('/')[2];
        console.log('onExchangeCounpon id', itemId);
        if (!this.isLogin()) {
            this.props.history.push('/glogin');
        } else {
            exchangeCoupon({items_id: itemId})
            .then((res) => {
                console.log(JSON.stringify(res));
                if (res && res.ret == 0) {
                    this.props.history.push(`/iframe?url=${res.data.coupon_click_url}`);
                } else {
                    alert(res.msg);
                }
            })
        }
    }
    render() {
        // window.BC_SDK = BCSDK_AppLink.init({
        //     appkey : '25419441', //必填，输入百川应用的appkey
        //     backURL: 'tbopen25419441', //必填，默认为空字符串，applink的tips的回跳url， 设置能在手机淘宝里面调回你自己应用的url，格式为`tbopen${appkey}`。
        //     openApp: true, //非必填，默认为true，非必填，是否唤起客户端，设置false，只会做H5跳转。
        //     linkKey: 'TB', //非必填，默认为TB, 唤起手淘(TB)/天猫(TM)。
        //     isNeedDownload: false, //非必填，默认为false, 没有app的情况下跳转目标h5页面还是下载页, 默认跳转目标h5页面。
        //     isDefaultRedirect: true, //选填, 没有唤起app的情况下是否默认跳转, 默认true。
        //     params:{}, //非必填，带给applink协议的扩展参数,用户自定义参数也传在这里, 如scm、pvid、pid、subpid、e、unionId等业务参数会放到这里。
        //     trackParams:{}, //非必填，ybhpss的映射对象，传入这里的参数会被拼为ybhpss字符串带到协议上。   
        //     timeout: 1000 // 非必填，默认跳转(目标h5页/下载页)的延时时长。
        //   });
        //   window.BC_SDK.gotoUrl({
        //     url : '//h5.m.taobao.com/awp/core/detail.htm?id=539488475784',
        //     params : {}
        //   });
        return (
            <div>
                 <Header title={ this.props.homepage.detail.title } onBack={this.props.clearDetail} />
                 <div id="detail-container"  ref={ref=>this.mainContent=ref}>
                    <Toast icon="loading" show={this.props.homepage.fetching}>Loading...</Toast>
                
                    <div className="swiper-container my-swiper1" ref="lun">
                    <div className="swiper-wrapper">
                    {this.props.homepage.detail.small_images && this.props.homepage.detail.small_images.length>0?this.props.homepage.detail.small_images.map((item, index) => {
                        return <div className="swiper-slide"><img src={ item } alt=""/></div>
                    }):""}
                    </div>
                    <div className='swiper-pagination my-pagination1'></div>
                    </div>
                    <div className="detail-data">
                        <div className="data-item">
                            <div className="item-title">
                                <img className="title-logo" src={require('../../../static/images2/list-logo.png')} alt=""/>
                                <div className="title-text">{ this.props.homepage.detail.title }</div>
                            </div>
                            <div className="item-middle">
                                原价: ￥{this.props.homepage.detail.zk_final_price}
                            </div>
                            <div className="item-foot">
                                <div className="foot-text"><div className="text-red">用券后</div><div className="foot-price">￥{ this.props.homepage.detail.coupon_after_price }</div></div>
                                <div className="foot-sale">已售{ this.props.homepage.detail.volume }</div>
                            </div>
                            <div className="item-coupon">
                                <div className="coupon-left">
                                    <div className="coupon-price"><span>{ this.props.homepage.detail.coupon_info }</span></div>
                                    <div className="coupon-date">使用有效期：{ this.props.homepage.detail.coupon_start_time }-{ this.props.homepage.detail.coupon_end_time }</div>
                                </div>
                                {/* <div className="coupon-right"><a href={ this.props.homepage.detail.coupon_short_url }>立即兑换</a></div> */}
                                {/* {<Link to={`/iframe?url=${this.props.homepage.detail.coupon_short_url}`}></Link>} */}
                                <div className="coupon-right" onClick={this.onExchangeCounpon}>立即兑换</div>
                            </div>
                            <div className="item-tips">领券后自动跳转到淘宝下单直接减免</div>
                        </div>
                        <div className="shop-data">
                            <img className="shop-icon" src={require('../../../static/images2/logo-qq.png')} alt=""/>
                            <p className="shop-name">{ this.props.homepage.detail.nick }</p>
                        </div>
                    </div>
                    <div className="share">
                        <button className="share-btn" 
                            onClick={this.onShare}
                        >
                            微信分享
                            <img className="shop-icon" src={require('../../../static/images2/list-logo.png')} alt=""/>
                        </button>
                    </div>
                    <div className="picture-article">
                        <div className="picture-title">
                            <span>图文详情
                                <img className="picture-icon" src={require('../../../static/images2/logo-tuwen.png')} alt=""/>
                            </span>
                            <img className="show-icon" src={require('../../../static/images2/logo-down2.png')} alt=""/>
                        </div>
                        <div className="picture-list">
                            {this.props.homepage.detail.items_content && this.props.homepage.detail.items_content.length>0? this.props.homepage.detail.items_content.map((item, index) => { 
                                return <img src={ item } alt=""/>
                            }):""}
                        </div>
                    </div>
                    <div className="like-list">
                        <div className="like-list-title">
                        <img src={require('../../../static/images2/list-left.png')} alt=""/>
                        <span className="t-text">猜你喜欢</span>
                        <img src={require('../../../static/images2/list-right.png')} alt=""/>
                        </div>
                        <List listClass={this.state.listClass} data={this.props.homepage.recommendGoodsList}></List>
                    </div>
                        
                </div>
                <div className="detail-fix">
                    <div className="fix-collect" onClick={this.onCollect.bind(this, this.props.location.pathname.split('/')[2])}>
                        <img src={this.state.isLike ? require('../../../static/images2/logo-like-2.png'): require('../../../static/images2/logo-cate-2.png')} alt="" />
                        <p>收藏</p>
                    </div>
                    <div className="fix-point">
                        <div className="point-data">积分：{(this.props.homepage.detail.zk_final_price-this.props.homepage.detail.coupon_after_price).toFixed(2)}</div>
                        <div className="point-date">有效期至{ this.props.homepage.detail.coupon_end_time }</div>
                    </div>
                    {/* <button className="fix-btn"><a href={ this.props.homepage.detail.coupon_short_url } target='_blank'>兑换优惠券</a></button> */}
                    {/* <Link to={`/iframe?url=${this.props.homepage.detail.coupon_short_url}`}>兑换优惠券</Link> */}
                    <button className="fix-btn" onClick={this.onExchangeCounpon}>兑换优惠券</button>
                </div>
            </div>
           
        )
    }
}

export default  withRouter(connect((state)=>{return {...state}}, actions)(Register));
